import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/transaction.dart';
import '../utils/format_util.dart';

class TransactionForm extends StatefulWidget {
  final Function(Transaction) onSubmit;
  final Function(Transaction)? onSubmitAndContinue;
  final Transaction? initialTransaction;

  const TransactionForm({
    super.key,
    required this.onSubmit,
    this.onSubmitAndContinue,
    this.initialTransaction,
  });

  @override
  State<TransactionForm> createState() => _TransactionFormState();
}

class _TransactionFormState extends State<TransactionForm> {
  String _amountString = '0.0';
  final _noteController = TextEditingController();
  bool _isSubmitting = false;

  late TransactionType _type;
  late Category _category;
  late DateTime _date;
  late String _currency;

  final List<String> _keyboardItems = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '.',
    '0',
    'BACKSPACE',
  ];

  @override
  void initState() {
    super.initState();
    if (widget.initialTransaction != null) {
      final transaction = widget.initialTransaction!;
      _amountString = transaction.amount
          .toStringAsFixed(2)
          .replaceAll('.00', '');
      _noteController.text = transaction.note ?? '';
      _type = transaction.type;
      _category = transaction.category;
      _date = transaction.date;
      _currency = transaction.currency;
    } else {
      _resetForm();
    }
  }

  void _resetForm() {
    _amountString = '0.0';
    _noteController.clear();
    _type = TransactionType.expense;
    _category = Category.food;
    _date = DateTime.now();
    _currency = 'CNY';
  }

  @override
  void dispose() {
    _noteController.dispose();
    super.dispose();
  }

  Future<void> _submit(bool addAnother) async {
    if (_isSubmitting) return;

    final amount = double.tryParse(_amountString);
    if (amount == null || amount == 0) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('金额不能为0')));
      return;
    }

    setState(() {
      _isSubmitting = true;
    });

    try {
      final transaction = Transaction(
        id: widget.initialTransaction?.id,
        title:
            _noteController.text.isNotEmpty
                ? _noteController.text
                : FormatUtil.getCategoryName(_category),
        amount: amount,
        date: _date,
        type: _type,
        category: _category,
        note: _noteController.text,
        currency: _currency,
      );

      if (addAnother && widget.onSubmitAndContinue != null) {
        await widget.onSubmitAndContinue!(transaction);
        setState(() {
          _resetForm();
        });
      } else {
        await widget.onSubmit(transaction);
        setState(() {
          _resetForm();
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSubmitting = false;
        });
      }
    }
  }

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _date,
      firstDate: DateTime(2020),
      lastDate: DateTime(2030),
    );
    if (picked != null && picked != _date) setState(() => _date = picked);
  }

  @override
  Widget build(BuildContext context) {
    final List<Category> expenseCategories =
        Category.values
            .where(
              (c) =>
                  c != Category.salary &&
                  c != Category.gift &&
                  c != Category.other,
            )
            .toList();
    final List<Category> incomeCategories = [
      Category.salary,
      Category.gift,
      Category.other,
    ];

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text('记一笔'),
        centerTitle: true,
        actions: [
          TextButton(
            onPressed: () => _submit(false),
            child: const Text(
              '保存',
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          // 金额输入区域
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 金额显示区域
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    TextButton(
                      onPressed: () {
                        showModalBottomSheet(
                          context: context,
                          builder:
                              (context) => _CurrencySelectionSheet(
                                onCurrencySelected: (currency) {
                                  setState(() {
                                    _currency = currency;
                                  });
                                },
                              ),
                        );
                      },
                      child: Text(
                        _currency,
                        style: const TextStyle(
                          fontSize: 32, // 与金额字体大小一致
                          color: Colors.black87,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    const Text(
                      '：', // 添加冒号
                      style: TextStyle(
                        fontSize: 32, // 与金额字体大小一致
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      _amountString,
                      style: const TextStyle(
                        fontSize: 32,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const Divider(height: 1),

          // 分类选择区域
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 支出分类
                  Text(
                    '支出',
                    style: Theme.of(context).textTheme.titleLarge?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Wrap(
                    spacing: 8.0,
                    runSpacing: 8.0,
                    children:
                        expenseCategories.map((category) {
                          final bool isSelected =
                              _category == category &&
                              _type == TransactionType.expense;
                          return ChoiceChip(
                            label: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  FormatUtil.getCategoryIcon(category),
                                  size: 18,
                                  color:
                                      isSelected
                                          ? Colors.white
                                          : Colors.black87,
                                ),
                                const SizedBox(width: 4),
                                Text(FormatUtil.getCategoryName(category)),
                              ],
                            ),
                            avatar:
                                isSelected
                                    ? const Icon(
                                      Icons.check,
                                      color: Colors.white,
                                      size: 18,
                                    )
                                    : null,
                            selected: isSelected,
                            onSelected: (selected) {
                              setState(() {
                                _type = TransactionType.expense;
                                _category = category;
                              });
                            },
                            selectedColor: Colors.green,
                            labelStyle: TextStyle(
                              color: isSelected ? Colors.white : Colors.black87,
                              fontSize: 14,
                            ),
                            backgroundColor: Colors.grey[200],
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16),
                              side: BorderSide(
                                color:
                                    isSelected
                                        ? Colors.green
                                        : Colors.grey[300]!,
                                width: 1,
                              ),
                            ),
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 8,
                            ),
                          );
                        }).toList(),
                  ),
                  const SizedBox(height: 24),

                  // 收入分类
                  Text(
                    '收入',
                    style: Theme.of(context).textTheme.titleLarge?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Wrap(
                    spacing: 8.0,
                    runSpacing: 8.0,
                    children:
                        incomeCategories.map((category) {
                          final bool isSelected =
                              _category == category &&
                              _type == TransactionType.income;
                          return ChoiceChip(
                            label: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  FormatUtil.getCategoryIcon(category),
                                  size: 18,
                                  color:
                                      isSelected
                                          ? Colors.white
                                          : Colors.black87,
                                ),
                                const SizedBox(width: 4),
                                Text(FormatUtil.getCategoryName(category)),
                              ],
                            ),
                            avatar:
                                isSelected
                                    ? const Icon(
                                      Icons.check,
                                      color: Colors.white,
                                      size: 18,
                                    )
                                    : null,
                            selected: isSelected,
                            onSelected: (selected) {
                              setState(() {
                                _type = TransactionType.income;
                                _category = category;
                              });
                            },
                            selectedColor: Colors.green,
                            labelStyle: TextStyle(
                              color: isSelected ? Colors.white : Colors.black87,
                              fontSize: 14,
                            ),
                            backgroundColor: Colors.grey[200],
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16),
                              side: BorderSide(
                                color:
                                    isSelected
                                        ? Colors.green
                                        : Colors.grey[300]!,
                                width: 1,
                              ),
                            ),
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 8,
                            ),
                          );
                        }).toList(),
                  ),
                ],
              ),
            ),
          ),

          // 数字键盘
          Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: TextButton(
                        onPressed: _selectDate,
                        child: Text(
                          DateFormat('yyyy-MM-dd').format(_date),
                          style: const TextStyle(
                            fontSize: 16,
                            color: Colors.black87,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: TextButton(
                        onPressed: () {
                          showModalBottomSheet(
                            context: context,
                            builder:
                                (context) => _NoteInputSheet(
                                  noteController: _noteController,
                                ),
                          );
                        },
                        child: Text(
                          _noteController.text.isEmpty
                              ? '添加备注'
                              : _noteController.text,
                          style: TextStyle(
                            fontSize: 16,
                            color:
                                _noteController.text.isEmpty
                                    ? Colors.grey
                                    : Colors.black87,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                GridView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    childAspectRatio: 2,
                    crossAxisSpacing: 8,
                    mainAxisSpacing: 8,
                  ),
                  itemCount: _keyboardItems.length,
                  itemBuilder: (context, index) {
                    final item = _keyboardItems[index];
                    if (item == 'BACKSPACE') {
                      return TextButton(
                        onPressed: () {
                          setState(() {
                            if (_amountString.length > 1) {
                              _amountString = _amountString.substring(
                                0,
                                _amountString.length - 1,
                              );
                            } else {
                              _amountString = '0.0';
                            }
                          });
                        },
                        child: const Icon(Icons.backspace_outlined),
                      );
                    }
                    return TextButton(
                      onPressed: () {
                        setState(() {
                          if (_amountString == '0.0') {
                            _amountString = item;
                          } else {
                            if (item == '.' && _amountString.contains('.')) {
                              return;
                            }
                            _amountString += item;
                          }
                        });
                      },
                      child: Text(item, style: const TextStyle(fontSize: 24)),
                    );
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _NoteInputSheet extends StatefulWidget {
  final TextEditingController noteController;

  const _NoteInputSheet({required this.noteController});

  @override
  State<_NoteInputSheet> createState() => _NoteInputSheetState();
}

class _NoteInputSheetState extends State<_NoteInputSheet> {
  bool _keyboardVisibleOnce = false;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    final bottomInset = MediaQuery.of(context).viewInsets.bottom;
    if (bottomInset > 0) {
      _keyboardVisibleOnce = true;
    }
    if (_keyboardVisibleOnce && bottomInset == 0 && mounted) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          Navigator.of(context).pop();
        }
      });
    }

    return Container(
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
      ),
      padding: const EdgeInsets.fromLTRB(20, 20, 12, 20),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: TextField(
              controller: widget.noteController,
              autofocus: true,
              textAlignVertical: TextAlignVertical.center,
              decoration: InputDecoration(
                hintText: '点击输入备注',
                filled: true,
                fillColor: colorScheme.surfaceContainerHighest.withValues(
                  alpha: 0.6,
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide.none,
                ),
                contentPadding: const EdgeInsets.symmetric(
                  vertical: 14,
                  horizontal: 16,
                ),
              ),
            ),
          ),
          const SizedBox(width: 8),
          IconButton(
            icon: const Icon(Icons.keyboard_arrow_down),
            iconSize: 28,
            onPressed: () => Navigator.of(context).pop(),
            color: colorScheme.onSurface.withValues(alpha: 0.6),
          ),
        ],
      ),
    );
  }
}

class _CurrencySelectionSheet extends StatelessWidget {
  final Function(String) onCurrencySelected;

  const _CurrencySelectionSheet({required this.onCurrencySelected});

  @override
  Widget build(BuildContext context) {
    final currencies = ['CNY', 'USD', 'EUR', 'GBP', 'JPY'];

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text(
            '选择货币',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 16),
          ...currencies.map(
            (currency) => ListTile(
              title: Text(currency),
              onTap: () {
                onCurrencySelected(currency);
                Navigator.pop(context);
              },
            ),
          ),
        ],
      ),
    );
  }
}
